import React, { useState, useEffect } from "react";
import { fetchClientCms } from "@/request/testAPI";

import styles from "./index.module.less";

const hexList: string[] = [];
for (let i = 0; i <= 15; i++) {
  hexList[i] = i.toString(16);
}

const buildUUID = () => {
  let uuid = "";
  for (let i = 1; i <= 36; i++) {
    if (i === 9 || i === 14 || i === 19 || i === 24) {
      uuid += "-";
    } else if (i === 15) {
      uuid += 4;
    } else if (i === 20) {
      uuid += hexList[(Math.random() * 4) | 8];
    } else {
      uuid += hexList[(Math.random() * 16) | 0];
    }
  }
  return uuid.replace(/-/g, "");
};

const QueryCard = () => {
  const [captchaStr, setCaptchaStr] = useState<string>("");
  const [_uuid, setuuid] = useState<string>(buildUUID());
  const [formData, setFormData] = useState({
    cardNumber: "",
    password: "",
    captcha: "",
  });

  useEffect(() => {
    if (_uuid) {
      setCaptchaStr(
        `${import.meta.env.VITE_API_BASE_URL}/jcaptcha.jpg?uuid=${_uuid}`
      );
    }
  }, [_uuid]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    console.log("Form submitted:", formData);
    console.log("_uuid:", _uuid);

    // const formDataBro = new FormData();
    // formDataBro.append("cardNo", formData.cardNumber);
    // formDataBro.append("password", formData.password);
    // formDataBro.append("jcaptcha", formData.captcha);
    const formDataBro = {
      cardNo: formData.cardNumber,
      password: formData.password,
      jcaptcha: formData.captcha,
    };

    const res = await fetchClientCms(formDataBro);
    console.log("登录返回", res);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  return (
    <div className={styles["query-card"]}>
      <div className={styles["title"]}>查询余额</div>

      <div className={styles["query-condition"]}>
        <form onSubmit={handleSubmit}>
          <div className={styles["condition-item"]}>
            <label htmlFor="cardNumber" className={styles["left-item"]}>
              卡号:
            </label>
            <input
              autoComplete="off"
              id="cardNumber"
              name="cardNumber"
              type="text"
              required
              pattern="^(2366|7310)\d{0,30}$"
              className={styles["right-item"]}
              placeholder="卡号必须是2366或7310开头的数字"
              value={formData.cardNumber}
              onChange={handleChange}
            />
          </div>
          <div className={styles["condition-item"]}>
            <label htmlFor="password" className={styles["left-item"]}>
              查询密码:
            </label>
            <input
              autoComplete="off"
              id="password"
              name="password"
              type="password"
              required
              className={styles["right-item"]}
              placeholder="请输入密码"
              value={formData.password}
              onChange={handleChange}
            />
          </div>
          <div className={styles["condition-item"]}>
            <label htmlFor="captcha" className={styles["left-item"]}>
              验证码:
            </label>
            <div
              className={styles["right-item-valid"]}
              style={{
                position: "relative",
              }}
            >
              <input
                autoComplete="off"
                id="captcha"
                name="captcha"
                type="text"
                required
                className={styles["right-item"]}
                style={{ width: 110, marginRight: 10 }}
                placeholder="请输入验证码"
                value={formData.captcha}
                onChange={handleChange}
              />
              <div
                className={styles["right-item"]}
                style={{ width: 126, padding: 0 }}
              >
                {captchaStr ? (
                  <img
                    style={{ display: "block", width: 123, height: 32 }}
                    src={captchaStr}
                    loading="lazy"
                  />
                ) : null}
              </div>
              <div
                className={styles["change-one"]}
                onClick={() => setuuid(buildUUID())}
              >
                看不清楚? 换一张
              </div>
            </div>
          </div>
          <div className={styles["condition-item"]}>
            <label
              className={styles["left-item"]}
              style={{ visibility: "hidden" }}
            >
              验证码:
            </label>
            <div className={styles["right-item-valid"]}>
              <button
                className={`${styles["right-item-btn"]}`}
                style={{ width: 136 }}
                type="submit"
              >
                查&nbsp;&nbsp;询
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
};

export default QueryCard;
